package com.hr.huangzhk.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

import com.hr.huangzhk.handler.MySocketHandler;
import com.hr.huangzhk.interceptor.WebSocketInterceptor;

/**
 * Created by huangzhk on 2016/10/20.
 */
@SpringBootApplication
@Configuration
@ComponentScan("com.hr.huangzhk")
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {

  @Autowired
  private MySocketHandler mySocketHandler;

  @Autowired
  private WebSocketInterceptor webSocketInterceptor;

  @Bean
  public ServletServerContainerFactoryBean createWebSocketContainer() {
    ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
    container.setMaxTextMessageBufferSize(8192);
    container.setMaxBinaryMessageBufferSize(8192);
    return container;
  }

  @Override
  public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
    webSocketHandlerRegistry.addHandler(mySocketHandler, "/ws")
        .addInterceptors(webSocketInterceptor);
    webSocketHandlerRegistry.addHandler(mySocketHandler, "/ws")
        .addInterceptors(webSocketInterceptor).withSockJS();
  }

  public static void main(String[] args) throws Exception {
    SpringApplication.run(WebSocketConfig.class, args);
  }

}
